import { Component, ReactNode } from "react";
import { View } from "@tarojs/components";
import Taro from "@tarojs/taro";
import Style from "./index.module.scss";
import classNames from "classnames";

// 定义组件的 props 类型
interface MyButtonClassProps {
  type?: string;
  children?: ReactNode;
  onBtnClick?: (e: any) => void;
}

export default class MyButtonClass extends Component<MyButtonClassProps> {
  instance = Taro.getCurrentInstance();

  // 1.组件生命周期
  constructor(props: MyButtonClassProps) {
    super(props);
    console.log("constructor");
  }

  state = {};

  shouldComponentUpdate(): boolean {
    console.log("shouldComponentUpdate");
    return true;
  }

  UNSAFE_componentWillMount() {
    // 监听页面的onReady生命周期
    const onReadyEventId = this.instance?.router?.onReady;
    if (onReadyEventId) {
      Taro.eventCenter.once(onReadyEventId, () => {
        console.log("Taro.eventCenter.once onReady");
      });
    } else {
      console.log("onReadyEventId is null");
    }

    console.log("UNSAFE_componentWillMount");
  }

  componentDidMount() {
    console.log("componentDidMount");
  }

  componentWillUnmount() {
    console.log("componentWillUnmount");
  }

  handleBtnClick(e: any) {
    this.props?.onBtnClick?.(e);
  }

  // 渲染函数
  render(): ReactNode {
    // 返回一个View组件，类名为MyButtonClass，内容为MyButtonClass
    return (
      <View
        className={classNames(
          Style["my-btn"],
          Style[this.props?.type || "default"]
        )}
        onClick={(e) => this.handleBtnClick(e)}
      >
        {this.props.children}
      </View>
    );
  }
}
